package server;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import server.command.CommandEnum;
import server.command.CommandFactory;

public class ServerHandler extends IoHandlerAdapter implements IDispatcher {

	private final Logger					logger		= (Logger) LoggerFactory.getLogger(getClass());
	private final Map<String, IoSession>	sessionMap	= Collections.synchronizedMap(new HashMap<String, IoSession>());
	private final IDispatcher				myRef		= this;

	@Override
	public void sessionOpened(IoSession session) {
		// set idle time to 10 seconds
		session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 6);
		session.setAttribute("Values: ");
	}

	public void messageReceived(IoSession session, Object message) {
		Message msg = (Message) message;
		System.out.println("---------");
		logger.info("Message received in the server..");
		logger.info("Message is: " + msg.getCommand() + "   " + msg.getParameters());
		CommandFactory cmd = new CommandFactory();
		(cmd.getCommand(CommandEnum.valueOf(msg.getCommand())).getInstance()).execute(session, msg.getParameters(), myRef);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) {
		logger.info("Disconnecting the idle.");
		// disconnect an idle client
		session.close(true);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) {
		// close the connection on exceptional situation
		session.close(true);
	}

	public synchronized void addSession(String username, IoSession session) {
		sessionMap.put(username, session);
	}

	public synchronized void removeSession(String username) {
		sessionMap.remove(username);
	}

	public boolean containsSessionForUser(String username) {
		return sessionMap.containsKey(username);
	}
}